import asyncio
import json
import time
from loguru import logger
from typing import Dict, Any


class PendingPaymentScheduler:
    """待付款订单检查调度器"""
    
    def __init__(self):
        self.running = False
        self.check_interval = 10  # 每10秒检查一次
        self.xianyu_instances = {}  # 存储XianyuLive实例 {cookie_id: xianyu_instance}
        
    def register_xianyu_instance(self, cookie_id: str, xianyu_instance):
        """注册XianyuLive实例"""
        self.xianyu_instances[cookie_id] = xianyu_instance
        logger.debug(f"注册XianyuLive实例到待付款检查调度器: {cookie_id}")
        
    def unregister_xianyu_instance(self, cookie_id: str):
        """注销XianyuLive实例"""
        if cookie_id in self.xianyu_instances:
            del self.xianyu_instances[cookie_id]
            logger.debug(f"从待付款检查调度器注销XianyuLive实例: {cookie_id}")
    
    async def start(self):
        """启动调度器"""
        if self.running:
            logger.warning("待付款检查调度器已在运行")
            return
            
        self.running = True
        logger.info("启动待付款订单检查调度器")
        
        # 记录上次清理时间
        last_cleanup_time = 0
        cleanup_interval = 3600  # 1小时清理一次
        
        while self.running:
            try:
                await self._process_pending_checks()
                
                # 定期清理旧记录
                current_time = asyncio.get_event_loop().time()
                if current_time - last_cleanup_time > cleanup_interval:
                    await self._cleanup_old_records()
                    last_cleanup_time = current_time
                
                await asyncio.sleep(self.check_interval)
            except Exception as e:
                logger.error(f"待付款检查调度器处理异常: {e}")
                await asyncio.sleep(self.check_interval)
    
    async def stop(self):
        """停止调度器"""
        self.running = False
        logger.info("停止待付款订单检查调度器")
    
    async def _process_pending_checks(self):
        """处理待检查的付款任务"""
        try:
            from db_manager import db_manager
            
            # 获取待处理的付款检查任务
            pending_tasks = db_manager.get_pending_payment_checks()
            
            if not pending_tasks:
                return
            
            logger.debug(f"发现 {len(pending_tasks)} 个待处理的付款检查任务")
            
            # 并发处理任务
            tasks = []
            for task in pending_tasks:
                tasks.append(self._process_single_check(task))
            
            if tasks:
                await asyncio.gather(*tasks, return_exceptions=True)
                
        except Exception as e:
            logger.error(f"处理待付款检查任务失败: {e}")
    
    async def _process_single_check(self, task: Dict[str, Any]):
        """处理单个付款检查任务"""
        try:
            from db_manager import db_manager
            
            task_id = task['id']
            cookie_id = task['cookie_id']
            order_id = task['order_id']
            user_id = task['user_id']
            item_id = task['item_id']
            
            logger.info(f"处理待付款检查任务: {task_id}, 订单: {order_id}, 账号: {cookie_id}")
            
            # 获取对应的XianyuLive实例
            xianyu_instance = self.xianyu_instances.get(cookie_id)
            if not xianyu_instance:
                logger.warning(f"未找到账号 {cookie_id} 的XianyuLive实例，跳过检查")
                db_manager.mark_pending_payment_check_completed(task_id)
                return
            
            # 使用API检查订单详情
            success = await self._check_order_payment_status(
                xianyu_instance, order_id, item_id, user_id, task_id
            )
            
            if success:
                logger.info(f"待付款检查任务 {task_id} 处理成功")
            else:
                logger.warning(f"待付款检查任务 {task_id} 处理失败")
            
            # 标记任务为已完成
            db_manager.mark_pending_payment_check_completed(task_id)
                
        except Exception as e:
            logger.error(f"处理待付款检查任务异常: {e}")
    
    async def _check_order_payment_status(self, xianyu_instance, order_id: str, item_id: str, user_id: str, task_id: int) -> bool:
        """检查订单付款状态并触发自动发货"""
        try:
            # 使用API获取订单详情
            from utils.order_detail_fetcher import fetch_order_detail_simple
            
            # 获取当前账号的cookie字符串
            cookie_string = xianyu_instance.cookies_str
            logger.debug(f"使用Cookie长度: {len(cookie_string) if cookie_string else 0}")
            
            # 使用API方式获取订单详情
            result = await fetch_order_detail_simple(order_id, cookie_string, headless=True, use_api=True)
            
            if not result:
                logger.warning(f"无法获取订单 {order_id} 的详情，跳过检查")
                return False
            
            # 获取订单状态信息
            order_main_title = None
            data_source = result.get('data_source', 'unknown')
            
            if data_source == 'api':
                # API方式：从原始API数据中提取orderMainTitle字段
                raw_data = result.get('raw_api_data')
                if not raw_data:
                    logger.warning(f"订单 {order_id} 详情中没有原始API数据")
                    return False
                
                # 添加调试日志，查看API数据结构
                logger.info(f"订单 {order_id} 原始API数据结构: {list(raw_data.keys()) if isinstance(raw_data, dict) else type(raw_data)}")
                if isinstance(raw_data, dict) and 'data' in raw_data:
                    logger.info(f"订单 {order_id} data字段结构: {list(raw_data['data'].keys()) if isinstance(raw_data['data'], dict) else type(raw_data['data'])}")
                    if isinstance(raw_data['data'], dict) and 'utArgs' in raw_data['data']:
                        logger.info(f"订单 {order_id} utArgs字段内容: {raw_data['data']['utArgs']}")
                
                # 从API数据中提取orderMainTitle
                try:
                    # 检查不同的可能路径
                    if 'utArgs' in raw_data:
                        # 直接在raw_data中查找utArgs
                        order_main_title = raw_data['utArgs'].get('orderMainTitle')
                        logger.info(f"订单 {order_id} 从raw_data.utArgs中找到orderMainTitle: {order_main_title}")
                    elif 'data' in raw_data and 'utArgs' in raw_data['data']:
                        # 在raw_data.data中查找utArgs
                        order_main_title = raw_data['data']['utArgs'].get('orderMainTitle')
                        logger.info(f"订单 {order_id} 从raw_data.data.utArgs中找到orderMainTitle: {order_main_title}")
                    
                    if not order_main_title:
                        logger.warning(f"订单 {order_id} 中未找到orderMainTitle字段")
                        # 输出utArgs的完整内容用于调试
                        if 'utArgs' in raw_data:
                            logger.info(f"订单 {order_id} utArgs完整内容: {raw_data['utArgs']}")
                        elif 'data' in raw_data and 'utArgs' in raw_data['data']:
                            logger.info(f"订单 {order_id} data.utArgs完整内容: {raw_data['data']['utArgs']}")
                        return False
                        
                except Exception as e:
                    logger.error(f"解析订单 {order_id} API状态失败: {e}")
                    return False
                    
            elif data_source == 'playwright':
                # Playwright方式：直接从结果中获取订单状态
                order_main_title = result.get('order_main_title') or result.get('order_status') or result.get('order_status_title')
                if order_main_title:
                    logger.info(f"订单 {order_id} 从Playwright数据中找到订单状态: {order_main_title}")
                else:
                    logger.warning(f"订单 {order_id} Playwright数据中未找到订单状态")
                    logger.info(f"订单 {order_id} Playwright结果字段: {list(result.keys())}")
                    return False
            else:
                logger.warning(f"订单 {order_id} 未知的数据源: {data_source}")
                return False
            
            if not order_main_title:
                logger.warning(f"订单 {order_id} 无法获取订单状态")
                return False
                
            logger.info(f"订单 {order_id} 状态: {order_main_title}")
            
            # 检查是否为需要自动发货的状态
            auto_delivery_statuses = [
                "买家已付款，请尽快发货",
                "买家已付款",
                "等待卖家发货"
            ]
            
            if any(status in order_main_title for status in auto_delivery_statuses):
                logger.info(f"订单 {order_id} 状态为 '{order_main_title}'，触发自动发货检查")
                
                # 触发自动发货逻辑
                await self._trigger_auto_delivery(xianyu_instance, order_id, item_id, user_id)
                return True
            else:
                logger.info(f"订单 {order_id} 状态为 '{order_main_title}'，不需要自动发货")
                return True
                
        except Exception as e:
            logger.error(f"检查订单 {order_id} 付款状态失败: {e}")
            return False
    
    async def _trigger_auto_delivery(self, xianyu_instance, order_id: str, item_id: str, user_id: str):
        """触发自动发货逻辑"""
        try:
            logger.info(f"开始触发订单 {order_id} 的自动发货逻辑")
            
            # 检查是否有对应的发货规则
            from db_manager import db_manager
            
            # 获取当前cookie的用户ID
            try:
                cookie_info = db_manager.get_cookie_by_id(xianyu_instance.cookie_id)
                current_user_id = cookie_info.get('user_id') if cookie_info else None
                logger.debug(f"当前用户ID: {current_user_id}")
            except Exception as e:
                logger.warning(f"获取用户ID失败: {e}")
                current_user_id = None
            
            # 检查是否有发货规则
            all_delivery_rules = db_manager.get_delivery_rules_by_item_id(item_id, current_user_id)
            
            if not all_delivery_rules:
                logger.warning(f"商品ID {item_id} 没有任何发货规则，跳过自动发货")
                return
            
            logger.info(f"找到 {len(all_delivery_rules)} 个发货规则，开始自动发货流程")
            
            # 获取订单详情信息用于发货
            order_detail = await xianyu_instance.fetch_order_detail_info(order_id, item_id, user_id)
            
            if not order_detail:
                logger.warning(f"无法获取订单 {order_id} 详情，跳过自动发货")
                return
            
            # 调用自动发货逻辑
            msg_time = time.strftime('%Y-%m-%d %H:%M:%S')
            
            # 模拟WebSocket消息结构，调用现有的自动发货处理逻辑
            # 需要包含订单ID信息，以便_extract_order_id能够提取到
            fake_message = {
                "1": {
                    "10": {
                        "1": user_id,  # 发送者ID
                        "2": "fake_message",  # 消息内容
                        "3": msg_time,  # 消息时间
                        "extJson": json.dumps({
                            "updateKey": f"{item_id}:{order_id}:paid_status"
                        })
                    },
                    "6": {
                        "5": json.dumps({
                            "contentType": 32,
                            "dynamicOperation": {
                                "changeContent": {
                                    "contentType": 26,
                                    "dxCard": {
                                        "item": {
                                            "main": {
                                                "targetUrl": f"fleamarket://order_detail?id={order_id}&role=seller"
                                            }
                                        }
                                    }
                                }
                            }
                        })
                    }
                }
            }
            
            # 调用自动发货处理方法
            await xianyu_instance._handle_auto_delivery(
                None,  # websocket (不需要)
                fake_message,
                f"用户{user_id}",  # send_user_name
                user_id,  # send_user_id
                item_id,  # item_id
                user_id,  # chat_id (使用user_id作为chat_id)
                msg_time  # msg_time
            )
            
            logger.info(f"订单 {order_id} 自动发货逻辑触发完成")
            
        except Exception as e:
            logger.error(f"触发订单 {order_id} 自动发货失败: {e}")
    
    async def _cleanup_old_records(self):
        """清理旧记录"""
        try:
            from db_manager import db_manager
            
            # 清理7天前的已完成或已取消的记录
            cursor = db_manager.get_connection().cursor()
            cursor.execute('''
            DELETE FROM pending_payment_checks 
            WHERE status IN ('completed', 'cancelled') 
            AND created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)
            ''')
            
            deleted_count = cursor.rowcount
            db_manager.conn.commit()
            
            if deleted_count > 0:
                logger.info(f"清理了 {deleted_count} 条旧的付款检查记录")
                
        except Exception as e:
            logger.error(f"清理旧付款检查记录失败: {e}")


# 创建全局调度器实例
pending_payment_scheduler = PendingPaymentScheduler()
